//
//  JWTLoginViewController.m
//  JWT
//
//  Created by Apple on 2017/1/1.
//  Copyright © 2017年 com.jwtsoft. All rights reserved.
//

#import "JWTLoginViewController.h"
#import "JWTForgetPWDViewController.h"
#import "JWTRegisterViewController.h"

#import "JWTUserHeaderView.h"


#define Margin 15
#define Layer_Color RGB(77,80,81)
//#define HeaderBackground_Color RGB(226,11,170)
#define TextField_Color RGB(241,241,242)
#define Text_Font13 [UIFont systemFontOfSize:13.0f]
#define Text_Font14 [UIFont systemFontOfSize:14.0f]
@interface JWTLoginViewController ()<UITextFieldDelegate>



@end

@implementation JWTLoginViewController

SHARED_INSTANCE_IMPLEMENTATION(JWTLoginViewController);

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initWithLeftBarItem];
    
    ///初始化视图
    [self initWithView];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(Add_UserPhoneTextAction:) name:@"Add_UserPhoneTextAction" object:nil];
}

-(void)Add_UserPhoneTextAction:(NSNotification *)notice{
    [self showPhoneNum];
}

-(void) showPhoneNum{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *phoneNumString = [userDefaults objectForKey:@"tel"];
    if (![phoneNumString isEqualToString:@""]) {
        _logPhoneTextField.text = phoneNumString;
    }
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


-(void) initWithView{
    
    WS(weakSelf);
    
    _headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.left, self.view.top, UISCREEN_WIDTH, (UISCREEN_HEIGHT-64)*0.35)];
//    _headerImageView.contentMode = UIViewContentModeScaleAspectFit;
    [_headerImageView setImage:[UIImage imageNamed:@"HeaderBackground"]];
    [self.view addSubview:_headerImageView];
    
    //图标
    _userImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.left,_headerImageView.bottom-90,90 ,90 )];
    [_userImageView setImage:[UIImage imageNamed:@"Login_UserIcon_default"]];
    _userImageView.layer.borderWidth = 0.5;
    _userImageView.layer.cornerRadius = _userImageView.height*0.5;
    _userImageView.layer.masksToBounds = YES;
    [self.view addSubview:_userImageView];
    _userImageView.center = CGPointMake(UISCREEN_WIDTH*0.5, _userImageView.center.y);
    
    //注册手机号
    _logPhoneTextField = [[JWTTextField alloc] initWithFrame:CGRectMake(UISCREEN_WIDTH*0.15, _userImageView.bottom+Margin*2, UISCREEN_WIDTH*0.7, 50)];
    _logPhoneTextField.layer.borderWidth = 0.5f;
    _logPhoneTextField.layer.cornerRadius = _logPhoneTextField.height * 0.5;
    _logPhoneTextField.layer.borderColor = Layer_Color.CGColor;
    _logPhoneTextField.clearButtonMode = UITextFieldViewModeAlways;
    _logPhoneTextField.delegate = self;
    _logPhoneTextField.placeholder = @"请输入手机号";
    [self.view addSubview:_logPhoneTextField];
    
    [self showPhoneNum];
    
    UIImageView *rephoneImageView = [[UIImageView alloc] initWithFrame:CGRectMake(Margin, 8, 34, 34)];
    [rephoneImageView setImage:[UIImage imageNamed:@"Phone"]];
    rephoneImageView.contentMode = UIViewContentModeScaleAspectFit;
    rephoneImageView.layer.masksToBounds = YES;
    _logPhoneTextField.leftViewMode=UITextFieldViewModeAlways;
    _logPhoneTextField.leftView.frame = CGRectMake(Margin, 8, 34, 34);
    _logPhoneTextField.leftView = rephoneImageView;
    
    //密码
    _logPassWordTextField = [[JWTTextField alloc] initWithFrame:CGRectMake(UISCREEN_WIDTH*0.15, _logPhoneTextField.bottom+Margin, UISCREEN_WIDTH*0.7, 50)];
    _logPassWordTextField.layer.borderWidth = 0.5f;
    _logPassWordTextField.layer.cornerRadius = _logPassWordTextField.height * 0.5;
    _logPassWordTextField.layer.borderColor = Layer_Color.CGColor;
    _logPassWordTextField.delegate = self;
    _logPassWordTextField.placeholder = @"请输入密码";
    _logPassWordTextField.clearButtonMode = UITextFieldViewModeAlways;
    _logPassWordTextField.secureTextEntry = YES;
    [self.view addSubview:_logPassWordTextField];
    
    UIImageView *resPassWordImageView = [[UIImageView alloc] initWithFrame:CGRectMake(Margin, 8, 34, 34)];
    [resPassWordImageView setImage:[UIImage imageNamed:@"PassWord"]];
    resPassWordImageView.contentMode = UIViewContentModeScaleAspectFit;
    resPassWordImageView.layer.masksToBounds = YES;
    _logPassWordTextField.leftViewMode=UITextFieldViewModeAlways;
    _logPassWordTextField.leftView.frame = CGRectMake(Margin, 8, 34, 34);
    _logPassWordTextField.leftView = resPassWordImageView;
    
    //注册
    _loginBtn = [[UIButton alloc] initWithFrame:CGRectMake(UISCREEN_WIDTH*0.25, _logPassWordTextField.bottom+Margin*2, UISCREEN_WIDTH*0.5, 50)];
    _loginBtn.layer.borderWidth = 0.5f;
    _loginBtn.layer.cornerRadius = _loginBtn.height * 0.5;
    _loginBtn.layer.borderColor = Layer_Color.CGColor;
    [_loginBtn setTitle:@"登 录" forState:UIControlStateNormal];
    [_loginBtn setTitleColor:RGB_WhiteBackGround forState:UIControlStateNormal];
    [_loginBtn setBackgroundColor:HeaderBackground_Color];
    [self.view addSubview:_loginBtn];
    //用户登录
    [_loginBtn addButtonBlockControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        [weakSelf userTelPhoneWithActionLogin];
    }];
    
    //已有账号
    _markWordLabel = [[UILabel alloc] initWithFrame:CGRectMake(_loginBtn.left-_loginBtn.width*0.5, _loginBtn.bottom+2*Margin, _loginBtn.width*0.6, 34)];
    _markWordLabel.textAlignment = NSTextAlignmentRight;
    _markWordLabel.text = @"还没有账号?";
    _markWordLabel.font = Text_Font13;
    [self.view addSubview:_markWordLabel];
    
    _registBtn = [[UIButton alloc] initWithFrame:CGRectMake(_markWordLabel.right+5, _markWordLabel.top, _loginBtn.width*0.4-5,_markWordLabel.height)];
    [_registBtn setTitle:@"注册" forState:UIControlStateNormal];
    [_registBtn setTitleColor:HeaderBackground_Color forState:UIControlStateNormal];
    _registBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    _registBtn.titleLabel.font = Text_Font14;
    [self.view addSubview:_registBtn];
    
    _forgetPWDBtn = [[UIButton alloc] initWithFrame:CGRectMake(_loginBtn.left+_loginBtn.width*0.8, _markWordLabel.top, _loginBtn.width*0.4-5,_markWordLabel.height)];
    [_forgetPWDBtn setTitle:@"忘记密码?" forState:UIControlStateNormal];
    [_forgetPWDBtn setTitleColor:HeaderBackground_Color forState:UIControlStateNormal];
    _forgetPWDBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    _forgetPWDBtn.titleLabel.font = Text_Font14;
    [self.view addSubview:_forgetPWDBtn];
    
    [_registBtn addButtonBlockControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        JWTRegisterViewController *vc = [[JWTRegisterViewController alloc] init];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    
    [_forgetPWDBtn addButtonBlockControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        JWTForgetPWDViewController *vc = [[JWTForgetPWDViewController alloc] init];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    
}

/**
 用户登录
 */
-(void) userTelPhoneWithActionLogin{
    if ([_logPhoneTextField.text isEqualToString:@""]) {
        [HUD showToast:@"手机号不能空"];
        return ;
    }else if ([[JWTCommons sharedInstance] validateMobile:_logPhoneTextField.text] == 0){
        [HUD showToast:@"手机号格式不正确"];
        return;
    }
    
    if ([_logPassWordTextField.text isEqualToString:@""]) {
        [HUD showToast:@"密码不能为空"];
        return;
    }else{
        if (_logPassWordTextField.text.length < 6) {
            [HUD showToast:@"密码长度不小于6位"];
            return;
        }
    }
    
//    dispatch_async(dispatch_get_main_queue(), ^{
        [self userLoginAction];
//    });
}

-(void) userLoginAction{
    [HUD showUIBlockingIndicator];
    NSString *urlString = [[JWTAPPHttpsUrl sharedInstance] getHttpsUrlWithActionLogin];
    
    NSDictionary *dict = @{@"tel":_logPhoneTextField.text,@"password":[NSString md5:_logPassWordTextField.text]};
    
    [AFNHttpsRequest requestWithUrl:urlString WithParam:dict WithGetDataDidFinishBlock:^(id model, NSURLSessionDataTask *task, NSError *error) {
        [self resignFirstResponseAction];
        [HUD hideUIBlockingIndicator];
        NSLog(@"%@",model);
        if (model) {
            [HUD showToast:[model objectForKey:@"message"]];
            if ([[model objectForKey:@"code"] integerValue] == 200) {
                APPDELEGATE.isLogin = YES;
                APPDELEGATE.userInfo = [JWTUserInfo mj_objectWithKeyValues:[model objectForKey:@"data"] ];
                
                //判断是否记住密码与自动登录
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setObject:APPDELEGATE.userInfo.tel forKey:@"tel"];
                [userDefaults setObject:APPDELEGATE.userInfo.name forKey:@"userName"];
                [userDefaults setObject:[NSString md5:_logPassWordTextField.text] forKey:@"passWord"];
                [userDefaults setObject:@"1" forKey:@"islogin"];
                [userDefaults setObject:APPDELEGATE.userInfo.tokenid forKey:@"tokenID"];
                [userDefaults synchronize];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"request_orderCourseAction" object:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"ReloadData_UserInfoNoticeAction" object:nil];
                [self.navigationController popViewControllerAnimated: YES];
            }else{
                [HUD showToast:[model objectForKey:@"message"]];
            }
        }
    }];

}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}

-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    CGFloat offset = self.view.frame.size.height - (textField.frame.origin.y+textField.frame.size.height+216+50);
    if (offset <= 0) {
        [UIView animateWithDuration:0.3 animations:^{
            CGRect frame = self.view.frame;
            frame.origin.y = offset;
            self.view.frame = frame;
        }];
    }
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect frame = self.view.frame;
        frame.origin.y = 64.0;
        self.view.frame = frame;
    }];
    return YES;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self resignFirstResponseAction];
}

-(void)navBack{
    [super navBack];
    [self resignFirstResponseAction];
}

-(void) resignFirstResponseAction{
    [_logPhoneTextField resignFirstResponder];
    [_logPassWordTextField resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
